package com.example.by.mdb.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.by.mdb.activity.App;
import com.example.by.mdb.R;
import com.example.by.mdb.activity.DianJian;
import com.example.by.mdb.activity.InspectionActivity;
import com.example.by.mdb.activity.MainActivity;
import com.example.by.mdb.db.MyDatabaseHelper;
import com.example.by.mdb.util.Util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by BY on 2016/1/5.
 */
public class MyTaskFragment extends Fragment {
    private View view;
    private TextView docVersion;
    private ListView myTaskListView;
    private ArrayList<String> id, name, totalCount, fileNames;
    private List completedCount;
    private SQLiteDatabase db;
    private MyTaskAdapter myTaskAdapter;
    private Button exportButton;
    //    private Spinner spinner;
    private Handler handler;
    //    private ArrayAdapter<String> spinnerAdapter;
    private LoadThread loadThread;
    private int index = 0;
    private App app;
    private AlertDialog dialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.my_task_fragment, null);
        init();
//        initSpinnerData();
//        spinnerAdapter.setDropDownViewResource(R.layout.dropdown_item);
//        spinner.setAdapter(spinnerAdapter);
//        spinner.setSelection(tableNames.size() - 1);
//        if (tableNames.size() > 0) {
//            app.setTxtName(tableNames.get(tableNames.size() - 1));
//        }

        initData();
        if (loadThread == null) {
            loadThread = new LoadThread();
            loadThread.start();
        }
        myTaskAdapter = new MyTaskAdapter();
        myTaskListView.setAdapter(myTaskAdapter);
//        spinner.setVisibility(View.INVISIBLE);
        return view;
    }

    private void deleteRecord() {
        File flag = new File(Environment.getExternalStorageDirectory(), "flag.txt");
        if (flag.exists()) {
            ArrayList eqps = new ArrayList();
            File lastEdit = new File(Environment.getExternalStorageDirectory(), "result_lastEdit.txt");
            BufferedReader br = null;
            try {
                String line = "";
                br = new BufferedReader(new FileReader(lastEdit));
                while ((line = br.readLine()) != null) {
                    String[] s = line.split(App.DIVIDE);
                    if (!eqps.contains(s[2])) {
                        eqps.add(s[2]);
                        System.out.println(s[2]);
                    }
                }
                br.close();
                for (int i = 0; i < eqps.size(); i++) {
                    db.delete("last_edit", "eqpno=?", new String[]{eqps.get(i) + ""});
                    db.delete("pda_check", "eqpno=?", new String[]{eqps.get(i) + ""});
                }
                flag.delete();
                lastEdit.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void refresh() {
        id.clear();
        name.clear();
        totalCount.clear();
        completedCount.clear();
//        spinnerAdapter.clear();
//        tableNames.clear();
        System.out.println("refresh");
//        initSpinnerData();
        initData();


        myTaskListView.setAdapter(myTaskAdapter);
    }

    @Override
    public void onResume() {
        deleteRecord();  //删除已经上传的记录
        refresh();
        index++;
        Date date = new Date();
        ArrayList list = new ArrayList();
        for (int i = 0; i < totalCount.size(); i++) {
            if (totalCount.get(i).equals(String.valueOf(completedCount.get(i)))) {
                list.add(name.get(i));
            }
        }
//        System.out.println("size:" + list.size());
        if (index > 1 && list.size() > 0) {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            String currentTime = format.format(date);
            String name = "result_lastEdit.txt";
            final File file = new File(Environment.getExternalStorageDirectory(), name);
            outPutFile(file, "last_edit", Util.fileName("pda_check"), list);
//        Toast.makeText(getContext(),"已保存到"+name,Toast.LENGTH_SHORT).show();
        }
        super.onResume();
    }
//
//    private void initSpinnerData() {
//        Cursor tableCursor = db.query("pda_check", new String[]{"file_name"}, null, null, null, null, null);
//        if (tableCursor.moveToFirst()) {
//            for (tableCursor.moveToFirst(); !tableCursor.isAfterLast(); tableCursor.moveToNext()) {
//                String fileName = tableCursor.getString(tableCursor.getColumnIndex("file_name"));
//                if (!tableNames.contains(fileName)) {
//                    tableNames.add(fileName);
//                    spinnerAdapter.add(fileName);
//                }
//            }
//        }
//        tableCursor.close();
//    }

//    private int getPosition() {
//        if (spinner.getSelectedItemPosition() < 0) {
//            return 0;
//        } else return spinner.getSelectedItemPosition();
//    }

    private void initData() {
        System.out.println("initData");


//        if (tableNames.size() > 0) {
        Cursor cursor = db.query("pda_check", new String[]{"eqpno"}, "file_name=? and groupno=?", new String[]{Util.fileName("pda_check"), app.getGroupNo()}, null, null, null);
        if (cursor.moveToFirst()) {
//            name.add(cursor.getString(cursor.getColumnIndex("eqpno")));
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String equName = cursor.getString(cursor.getColumnIndex("eqpno"));
                if (!name.contains(equName)) {
                    name.add(equName);
                    Cursor count = db.query("pda_check", new String[]{"eqpno"}, "eqpno=? and file_name=? and groupno = ?", new String[]{equName, Util.fileName("pda_check"), app.getGroupNo()}, null, null, null);
                    totalCount.add(count.getCount() + "");
                    Cursor count1 = db.query("pda_check", new String[]{"flag"}, "eqpno=? and flag=? and file_name=? and groupno = ?", new String[]{equName, "1", Util.fileName("pda_check"), app.getGroupNo()}, null, null, null);
                    completedCount.add(count1.getCount());
                    id.add(id.size() + 1 + "");
                    count.close();
                    count1.close();
                }
            }
        }
        for (int i = 0; i < totalCount.size(); i++) {
            if ((totalCount.get(i) + "").equals(completedCount.get(i) + "")) {
                name.add(name.get(i));
                totalCount.add(totalCount.get(i));
                completedCount.add(completedCount.get(i));
                name.remove(i);
                totalCount.remove(i);
                completedCount.remove(i);
            }
        }
        cursor.close();
//        }
//        MainActivity activity = (MainActivity) getActivity();
//        String grade = activity.groupNo;
//        System.out.println("grade:" + grade);
//        if (grade.equals("2")) {
//            for (int i = 0; i < name.size(); i++) {
//                if (name.get(i).equals("CMP111")) {
//                    name.remove(i);
//                    totalCount.remove(i);
//                    completedCount.remove(i);
//                    id.clear();
//                    for (int j = 0; j < name.size(); j++) {
//                        id.add(id.size() + 1 + "");
//                    }
//                }
//            }
//        }
    }

    private void init() {
        app = (App) getActivity().getApplication();
        dialog = new AlertDialog.Builder(getContext()).create();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {
                    case 0:
//                        Toast.makeText(getContext(), "更新完成", Toast.LENGTH_SHORT).show();

                        refresh();
//                        spinner.setAdapter(spinnerAdapter);
//                        spinner.setSelection(tableNames.size() - 1);
//                        app.setTxtName(tableNames.get(tableNames.size() - 1));
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        break;
                    case 1:
//                        Toast.makeText(getContext(), "有新数据，正在更新...", Toast.LENGTH_SHORT).show();
                        LayoutInflater inflater = LayoutInflater.from(getContext());
                        View view = inflater.inflate(R.layout.progress, null);
//                        ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
                        dialog.setView(view);
                        dialog.setCancelable(false);
                        dialog.show();
//                        break;
                    case 2:
//                        Toast.makeText(getContext(), "无新数据", Toast.LENGTH_SHORT).show();
//                        System.out.println("count:  " + name.size());
//                        dialog.dismiss();
                        break;
                }
                super.handleMessage(msg);
            }
        };
        MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(getContext(), "pda.db");
        db = myDatabaseHelper.getReadableDatabase();
        id = new ArrayList<>();
        name = new ArrayList<>();
        totalCount = new ArrayList<>();
        completedCount = new ArrayList<>();
        fileNames = new ArrayList<>();
//        tableNames = new ArrayList<String>();
        docVersion = (TextView) view.findViewById(R.id.docVersion);
        docVersion.setText("文档版本: IOC（HH）-W-8001-4");
        myTaskListView = (ListView) view.findViewById(R.id.mytaskListView);
//        spinner = (Spinner) view.findViewById(R.id.spinner);
//        spinnerAdapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item);
        exportButton = (Button) view.findViewById(R.id.exportButton);
        exportButton.setVisibility(View.INVISIBLE);
//        exportButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                final File file = new File(Environment.getExternalStorageDirectory(), "result_lastEdit.txt");
//                final File result_maintain = new File(Environment.getExternalStorageDirectory(), "result_maintain.txt");
//                if (file.exists() || result_maintain.exists()) {
//                    final AlertDialog.Builder alert = new AlertDialog.Builder(getContext(), AlertDialog.THEME_HOLO_LIGHT);
//                    alert.setMessage("文件已存在，继续将覆盖原文件");
//                    alert.setNegativeButton("取消操作", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                        }
//                    });
//                    alert.setPositiveButton("确定导出", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            outPutFile(file, "last_edit");
//                            outPutFile(result_maintain, "result_maintain");
//                        }
//                    });
//                    alert.show();
//                } else {
//                    outPutFile(file, "last_edit");
//                    outPutFile(result_maintain, "result_maintain");
//                }
//
//            }
//        });
//        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//
//                refresh();
//
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });
    }


    private void outPutFile(File file, String table, String fileName, ArrayList list) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            Cursor cursor = db.query(table, null, "file_name=?", new String[]{fileName}, null, null, null);
            if (cursor.moveToFirst()) {
                String[] cursorNames = cursor.getColumnNames();
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    if (list.contains(cursor.getString(cursor.getColumnIndex("eqpno")))) {
                        for (int i = 1; i < cursorNames.length - 1; i++) {
                            if (i == cursorNames.length - 2) {
                                if (cursor.getString(cursor.getColumnIndex(cursorNames[i])).equals("")) {
                                    bw.append("null");
                                } else {
                                    bw.append(cursor.getString(cursor.getColumnIndex(cursorNames[i])));
                                }
                            } else {
                                if (cursor.getString(cursor.getColumnIndex(cursorNames[i])).equals("")) {
                                    bw.append("null" + App.DIVIDE);
                                } else {
                                    bw.append(cursor.getString(cursor.getColumnIndex(cursorNames[i])) + "<-->");
//                            System.out.println(table + ": " + cursor.getString(cursor.getColumnIndex(cursorNames[i])));
                                }
                            }
                        }
                    }
                    bw.newLine();
                }
            }
            System.out.println("output"+bw.toString());
            cursor.close();
            bw.flush();
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyTaskAdapter extends BaseAdapter {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        Intent intent = new Intent(getContext(), DianJian.class);

        @Override
        public int getCount() {
            return id.size();
        }

        @Override
        public Object getItem(int position) {
            return id.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = inflater.inflate(R.layout.list_item, null);
                viewHolder.layout = (LinearLayout) convertView.findViewById(R.id.listLayout);
                viewHolder.id = (TextView) convertView.findViewById(R.id.id);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.totalCount = (TextView) convertView.findViewById(R.id.totalCount);
                viewHolder.compeletedCount = (TextView) convertView.findViewById(R.id.compeletedCount);
                viewHolder.startInspection = (Button) convertView.findViewById(R.id.startInspection);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.id.setText((CharSequence) id.get(position));
            viewHolder.name.setText((CharSequence) name.get(position));
            viewHolder.totalCount.setText((CharSequence) totalCount.get(position));
            viewHolder.compeletedCount.setText(String.valueOf(completedCount.get(position)));
            if ((totalCount.get(position) + "").equals(completedCount.get(position) + "")) {
                viewHolder.startInspection.setText("点检完成");
                viewHolder.layout.setBackgroundColor(Color.GREEN);
            } else if (!String.valueOf(completedCount.get(position)).equals("0")) {
                viewHolder.startInspection.setText("继续点检");
                viewHolder.layout.setBackgroundColor(Color.WHITE);
            } else {
                viewHolder.layout.setBackgroundColor(Color.WHITE);
            }
            viewHolder.startInspection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("eqpno", name);
                    bundle.putInt("index", position);
                    bundle.putString("name", name.get(position));
                    bundle.putString("table", "pda_check");
                    bundle.putString("fileName", Util.fileName("pda_check"));
                    intent.putExtra("eqpno", bundle);
                    startActivity(intent);
                }
            });
            return convertView;
        }

        private class ViewHolder {
            TextView id;
            TextView name;
            TextView totalCount;
            TextView compeletedCount;
            Button startInspection;
            LinearLayout layout;
        }
    }

    class LoadThread extends Thread {
        File path = Environment.getExternalStorageDirectory();
        File[] files = path.listFiles();
        private boolean hasNewData = false;

        public LoadThread() {

        }

        @Override
        public void run() {
            fileNames = getFileName(files);
            for (Object fileName : fileNames) {
                String name = fileName + ".txt";
                File file = new File(Environment.getExternalStorageDirectory(), name);
                String sql = null;
                String table = "";
                if (name.contains("pda_check")) {
                    table = "pda_check";
                    sql = "insert into pda_check(eqpno,edition,checkno,rank,groupno,checkitem1,checkitem2,checkitem3,item,standard1,standard2,unit,type,notice,frequency,rst_ng,file_name) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                }
// else if (name.contains("pda_maintain")) {
//                    table = "pda_maintain";
//                    sql = "insert into pda_maintain(eqpno,edition,checkno,rank,groupno,checkitem1,checkitem2,checkitem3,item,standard1,standard2,unit,type,notice,frequency,rst_ng,file_name) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//                }
                importFile(file, sql, table);
            }
            if (hasNewData) {
                handler.sendEmptyMessage(0);
            } else {
                handler.sendEmptyMessage(2);
            }
        }

        private void importFile(File file, String SQL, String table) {
            String[] name = file.getName().split("\\.");
            Cursor check = db.query("record", null, "file_name=?", new String[]{name[0]}, null, null, null);
            if (!check.moveToFirst()) {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new FileReader(file));
                    String line = br.readLine();

                    String[] s2 = line.split(App.DIVIDE);
//                System.out.println(s2[0] + "   " + s2[2] + "   " + name[0]);
                    Cursor cursor = db.query(table, new String[]{"eqpno"}, "eqpno=? and checkno=? and file_name=?", new String[]{s2[0], s2[2], name[0]}, null, null, null);
                    db.beginTransaction();
                    if (!cursor.moveToFirst()) {
                        br = new BufferedReader(new FileReader(file));
                        while ((line = br.readLine()) != null) {
                            String[] s = line.split(App.DIVIDE);
                            String[] s1 = Arrays.copyOf(s, s.length + 1);
                            s1[s.length] = name[0];
//                    Cursor cursor = db.query(table, new String[]{"eqpno"}, "eqpno=? and checkno=? and file_name=?", new String[]{s1[0], s1[2], name[0]}, null, null, null);

                            if (!hasNewData) {
                                handler.sendEmptyMessage(1);
                            }
                            hasNewData = true;
                            db.execSQL(SQL, s1);
//                        db.setTransactionSuccessful();
                            System.out.println(line.toString() + "   " + name[0]);
                        }
                        cursor.close();
                    }
                    db.setTransactionSuccessful();
                    db.endTransaction();
//                file.delete();
                    br.close();
                    db.execSQL("insert into record(file_name) values(?)", new String[]{name[0]});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private ArrayList getFileName(File[] files) {
            ArrayList fileNames = new ArrayList();
            if (files != null) {
//                name = new ArrayList();
                for (File file : files) {
                    String fileName = file.getName();
                    if (fileName.startsWith("pda")) {
//                        System.out.println(fileName);
                        String[] name = fileName.split("\\.");
//                        System.out.println(name[0]);
                        fileNames.add(name[0]);
                    }
                }
            }
            return fileNames;
        }
    }
}
